//
//  SigningViewController.m
//  JinChengYun
//
//  Created by 金橙云 on 2017/3/3.
//  Copyright © 2017年 金橙云. All rights reserved.
//

#import "SigningViewController.h"

#import "MySigningCell.h"
#import "TodoHttpManager.h"
#import "BusQianXViewController.h"
#import "FTPopOverMenu.h"
@interface SigningViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

{
    NSMutableArray *_zongArr;
    NSMutableDictionary *_busGouDic;
    
    //全局view,好对其删除.
    UIView*view;
    //建两个全局的,来记录你点击了什么
    NSString *one;
    NSString *tow;
    NSString *uid;
    
    NSString *IDA;
    NSString *keStr;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UISearchBar *suoSearchBar;
@end

@implementation SigningViewController
-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDGMQianYue:) name:TDGMQianYue object:nil];
    NSUserDefaults *userDefa = [NSUserDefaults standardUserDefaults];
   uid= [userDefa objectForKey:@"USER_ID"];
    //TODO:我的签约
    [_manager userGMShnagQianYueWithID:uid withSouSuo:nil withSouType:nil withHuiK:nil];
}

-(void)didTDGMQianYue:(NSNotification *)notifi
{
    if (notifi.object != nil)
    {
        int status = [[notifi.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
            _busGouDic = [notifi.object objectForKey:@"data"];
            _zongArr = [_busGouDic objectForKey:@"data"];
            if (_zongArr.count != 0)
            {
                NSString *taoStr = [_busGouDic objectForKey:@"sale_rooms"];
                NSString *jinStr = [_busGouDic objectForKey:@"sale_money"];
                [self setupViewWithTaoSh:taoStr withMoney:jinStr];
                
            }
            else
            {
                if ([NSString stringWithFormat:@"%@", [notifi.object objectForKey:@"info"]].length>0) {
                    [_manager MakeMyselfAlert:[notifi.object objectForKey:@"info"] andIsNeedTitle:NO andShowTime:2];
                }
                
            }
            [_tableView reloadData];
        }
        else
        {
            [_manager MakeMyselfAlert:@"获取失败" andIsNeedTitle:NO andShowTime:2];
        }
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDGMQianYue object:nil];
    
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"签约";

    _zongArr = [NSMutableArray arrayWithCapacity:0];
    _manager = [TodoHttpManager sharedManager];
    _busGouDic = [[NSMutableDictionary alloc] init];
    IDA = [[NSUserDefaults standardUserDefaults] objectForKey:@"STATE"];
    if ([IDA isEqualToString:@"1"])
    {
        _suoSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30, B_WIDTH, 44)];
        _suoSearchBar.delegate = self;
        [_suoSearchBar setPlaceholder:@"输入搜索内容"];
        [self.view addSubview:_suoSearchBar];
        
    }
    else if ([IDA isEqualToString:@"2"])
    {
        UIButton *zuoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        zuoBtn.frame = CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30, 50, 44);
        zuoBtn.backgroundColor = [UIColor colorWithHexString:@"#c9c9ca"];
        zuoBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [zuoBtn setTitle:@"  客户" forState:0];
        keStr = @"0";
        [zuoBtn setTitleColor:[UIColor blackColor] forState:0];
        [zuoBtn addTarget:self action:@selector(busQianBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [zuoBtn setImage:[UIImage imageNamed:@"Btn_SanJiao"] forState:0];
        [zuoBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:3];
        [self.view addSubview:zuoBtn];
        _suoSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(50, LL_StatusBarAndNavigationBarHeight+30, B_WIDTH-50, 44)];
        _suoSearchBar.delegate = self;
        [_suoSearchBar setPlaceholder:@"输入搜索内容"];
        [self.view addSubview:_suoSearchBar];
    }

   
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(busYueXuanBtnClick)];
    
    self.navigationItem.rightBarButtonItem = rightBarItem;
    [self.navigationItem.rightBarButtonItem setImage:[[UIImage imageNamed:@"Btn_seacher"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30+44, B_WIDTH, B_HEIGHT-(LL_StatusBarAndNavigationBarHeight+30+44)) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 60;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];

    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(qianYueRefersh)];
}

-(void)qianYueRefersh
{
     [_manager userGMShnagQianYueWithID:uid withSouSuo:nil withSouType:nil withHuiK:nil];
    [self.tableView.mj_header endRefreshing];
}
-(void)setupViewWithTaoSh:(NSString *)_tao withMoney:(NSString *)_money
{
    UIView *aVi = [[UIView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, B_WIDTH, 30)];
    aVi.backgroundColor = [UIColor colorWithHexString:@"#eb6200"];
    [self.view addSubview:aVi];
    UILabel *oneLab = [[UILabel alloc] init];
    oneLab.textColor = [UIColor whiteColor];
    oneLab.font = [UIFont systemFontOfSize:14];
    oneLab.text = [NSString stringWithFormat:@"套数: %@",_tao];
    [aVi addSubview:oneLab];
    [oneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        make.left.equalTo(aVi.mas_left).offset(20);
        make.top.equalTo(aVi.mas_top).offset(5);
        
    }];
    
    
    UILabel *twLab = [[UILabel alloc] init];
    twLab.textColor = [UIColor whiteColor];
    twLab.font = [UIFont systemFontOfSize:14];
    twLab.text = [NSString stringWithFormat:@"|   金额:%@ 元",_money];
    [aVi addSubview:twLab];
    [twLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(160, 20));
        make.left.equalTo(oneLab.mas_right).offset(5);
        make.top.equalTo(aVi.mas_top).offset(5);
        
    }];
    
    
    
    
}
-(void)busYueXuanBtnClick
{
    //    创建一个View;
    view=[[UIView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, self.view.frame.size.width, 130)];
    view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view];
    
    UILabel *typeLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 8, 100, 20)];
    typeLab.font = [UIFont systemFontOfSize:12];
    typeLab.text = @"回款状态";
    [view addSubview:typeLab];
    
    //线
    
    UILabel *linLab = [[UILabel alloc] init];
    linLab.frame = CGRectMake(0, 62, B_WIDTH, 0.5);
    linLab.backgroundColor = [UIColor grayColor];
    [view addSubview:linLab];
    
    NSArray *titArr= @[@"已回款",@"未回款"];
    int AA = (B_WIDTH-20*2-20)/2;
    for (int m = 0; m <2; m++)
    {
        UIButton *chengBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        chengBtn.frame = CGRectMake(20+AA*m, 35, AA-10, 20);
        chengBtn.layer.cornerRadius = 2;
        chengBtn.layer.borderWidth = 0.5;
        chengBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [chengBtn setTitleColor:[UIColor blackColor] forState:0];
        chengBtn.layer.borderColor = [UIColor grayColor].CGColor;
        chengBtn.tag = 1000+m;
        [chengBtn addTarget:self action:@selector(AddBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [chengBtn setTitle:titArr[m] forState:UIControlStateNormal];
        [view addSubview:chengBtn];
        
    }
    
    
    
    //确定按钮
    
    UIButton*determineBtn=[[UIButton alloc]initWithFrame:CGRectMake(10, 75, B_WIDTH-10*2, 35)];
    determineBtn.layer.cornerRadius = 5;
    [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
    [determineBtn addTarget:self action:@selector(determineBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    determineBtn.backgroundColor=[UIColor orangeColor];
    [view addSubview:determineBtn];
    
}
//四个按钮的点击事件,用来记录点击了什么
-(void)AddBtnClick:(UIButton*)btn
{
    UIButton*btn1=[self.view viewWithTag:1000];
    UIButton*btn2=[self.view viewWithTag:1001];
    
    
    if (btn.tag==1000) {
        //点击了一排第一个
        one=@"1";
        btn1.backgroundColor=[UIColor orangeColor];
        btn2.backgroundColor=[UIColor whiteColor];
    }else if (btn.tag==1001)
    { //点击了一排第二个
        one= @"2";
        btn2.backgroundColor=[UIColor orangeColor];
        btn1.backgroundColor=[UIColor whiteColor];
        
    }
}

//确定按钮的点击事件,用来掉接口
-(void)determineBtnClick:(UIButton *)btn
{
    NSLog(@"走这一步了没有%@",one);
    //点击后直接进行删除view
    [view removeFromSuperview];
    //然后调接口
    
    [_manager userGMShnagQianYueWithID:uid withSouSuo:nil withSouType:@"0" withHuiK:one];

    
    [_tableView reloadData];
    //最后让两个int归零,方便下次点击继续记录
    one=@"0" ;
    tow=@"0";
}

#pragma mark- 搜索的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    if ([IDA isEqualToString:@"1"])
    {
        [_manager userGMShnagQianYueWithID:uid withSouSuo:searchBar.text withSouType:nil withHuiK:nil];

        
        [_tableView reloadData];
    }
    if ([IDA isEqualToString:@"2"])
    {
         [_manager userGMShnagQianYueWithID:uid withSouSuo:searchBar.text withSouType:keStr withHuiK:nil];
        
        [_tableView reloadData];
    }
    
      //让键盘失去第一响应者
    [searchBar resignFirstResponder];
    
    
    
}

//当搜索框中的内容发生改变时会自动进行搜索,这个是经常用的

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if (searchText.length == 0) {
        [_manager userGMShnagQianYueWithID:uid withSouSuo:nil withSouType:@"0" withHuiK:nil];     [searchBar resignFirstResponder];
        
        [_tableView reloadData];
    }else {
        
         [_manager userGMShnagQianYueWithID:uid withSouSuo:searchText withSouType:@"0" withHuiK:nil];
        //更新UI
        [_tableView reloadData];
    }
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _zongArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndent = @"Cell";
    MySigningCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndent];
    if (!cell)
    {
        cell = [[MySigningCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndent];
        
    }
    if ([cell isKindOfClass:[MySigningCell class]])
    {
        if (_zongArr.count != 0)
        {
            NSDictionary *dict = [_zongArr objectAtIndex:indexPath.row];

            [(MySigningCell *)cell setUpCellQianYUeWithName:dict[@"rengou_name"] andHouse:dict[@"room_name"] andRenDate:dict[@"sign_time"] andShouSty:dict[@"hk_status"] andPhone:dict[@"rengou_phone"] andGuWen:dict[@"adviser"]];

        }
    }

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];//取消点击
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BusQianXViewController *busQianX = [[BusQianXViewController alloc] init];
    busQianX.idStr = [[_zongArr objectAtIndex:indexPath.row] objectForKey:@"id"];
    [self.navigationController pushViewController:busQianX animated:NO];
    
}

#pragma mark--客户员工选择
-(void)busQianBtnClick:(UIButton *)sender
{
    NSArray *arr = @[@"客户",@"员工",];
    [FTPopOverMenu showForSender:sender
                   withMenuArray:arr
                      imageArray:nil
                       doneBlock:^(NSInteger selectedIndex)//0 . . . .
     {
         [sender setTitle:arr[selectedIndex] forState:UIControlStateNormal];
         
         NSString *yuanStr = arr[selectedIndex];
         
         if ([yuanStr isEqualToString:@"员工"])
         {
             keStr = @"1";
         }
         else
         {
             keStr = @"0";
         }
         
     }
                    dismissBlock:^
     {
         
     }];
    
}

#pragma mark- 关闭键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_suoSearchBar resignFirstResponder];
    
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_suoSearchBar resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
